package com.toommi.refuse.listener;

import com.toommi.refuse.common.util.GsonUtil;
import com.toommi.refuse.entity.PermissionGroup;
import com.toommi.refuse.entity.SysPermission;
import com.toommi.refuse.service.admin.SysPermissionGroupService;
import com.toommi.refuse.service.admin.SysPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class PermissionInterface implements IPermissionInterface {

    @Resource
    private SysPermissionService sysPermissionService;

    @Resource
    private SysPermissionGroupService groupService;


    @Override
    public int order() {
        return 0;
    }

    @Override
    public void execute(Object... objects) {

        Object groupList = objects[0];
        Object permissionList = objects[1];

        List<PermissionGroup> permissionGroupList = (List<PermissionGroup>) groupList;

        List<SysPermission> sysPermissions = (List<SysPermission>) permissionList;

        // 执行权限上报
        for (PermissionGroup permissionGroup : permissionGroupList) {
            if (groupService.findGroupByCode(permissionGroup.getCode()) == null) {
                log.debug("execute permission group add :{}", GsonUtil.toJson(permissionGroup));
                groupService.addPermissionGroup(permissionGroup);
            }
        }

        for (SysPermission sysPermission : sysPermissions) {
            //校验权限是否已经存在
            if (sysPermissionService.findPermissionByCode(sysPermission.getPerssionCode()) == null) {
                log.debug("execute permission add :{}", GsonUtil.toJson(sysPermission));
                sysPermissionService.addPermission(sysPermission);
            }
        }

    }


}